import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/color_constants.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bean/binding_terminal_edit_upload_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/bind_terminal_info_confirm_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_number_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_pic_detail_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/scan_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/channel_org_list_page.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'channel_org_list_view_model.dart';
import 'new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:vg_base/vg_permission_lib.dart';

class ScanBindTerminalPage extends StatefulWidget{
  static const ROUTER = "ScanBindTerminalPage";
  final String gps;
  final String hsn;
  final ScanResultBean data;
  const ScanBindTerminalPage({Key key, this.gps, this.data, this.hsn}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ScanBindTerminalPageState();

  static Future<bool> navigatorPush(
      BuildContext context, String gps, ScanResultBean data, String hsn) {
    return RouterUtils.routeForFutureResult(
        context,
        ScanBindTerminalPage(
          gps: gps,
          data: data,
          hsn: hsn,
        ),
        routeName: ScanBindTerminalPage.ROUTER);
  }
}

class _ScanBindTerminalPageState extends BaseState<ScanBindTerminalPage>{
  String _terminalPicUrl;
  String _position;
  String _backup;
  String _gps;
  NewTerminalListViewModel _viewModel;
  ScanResultBean _data;
  CompanyAddressListInfoBean _selectAddress;
  VgLocation _locationPlugin;

  TextEditingController _positionController;
  TextEditingController _backupController;
  int _index = -1;

  FocusNode _positionFocusNode;
  FocusNode _backupFocusNode;

  @override
  void initState() {
    super.initState();
    _positionFocusNode = FocusNode();
    _backupFocusNode = FocusNode();
    _positionFocusNode.addListener(() {
      if (_positionFocusNode?.hasFocus ?? false) {
        setState(() {        _index = 1; });
      }
    });
    _backupFocusNode.addListener(() {
      if (_backupFocusNode?.hasFocus ?? false) {
        setState(() {        _index = 2; });
      }
    });
    _positionController = TextEditingController();
    _backupController = TextEditingController();
    _gps = widget?.gps;
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocation((value) {
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        print("获取到了最新gps:" + value);
        _gps = value;
      });
    });
    _data = widget?.data;
    _viewModel = NewTerminalListViewModel(this, gps: _gps);
    _viewModel.refresh();
    _viewModel.getAddressList(context);
  }

  @override
  void dispose() {
    _positionFocusNode?.dispose();
    _backupFocusNode?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ColorConstants.BG_OR_SPLIT_COLOR,
      body: CommonPackUpKeyboardWidget(
        child: Column(
          children: [
            _toTopBarWidget(),
            SizedBox(height: 20,),
            _toCompanyWidget(),
            SizedBox(height: 15,),
            _toEmptyWidget(),
            _toChannelOrgWidget(),
            Visibility(
              visible: AppOverallDistinguish.comefromAiOrWeStudy(),
              child: Container(
                child: _toDividerWidget((0 == _index)?Color(0xFF1890ff):Color(0xFF303546)),
              ),
            ),
            Visibility(
                visible: AppOverallDistinguish.comefromAiOrWeStudy(),
                child: SizedBox(height: 15,)
            ),
            _toPositionWidget(),
            _toDividerWidget((1 == _index)?Color(0xFF1890ff):Color(0xFF303546)),
            SizedBox(height: 15,),
            _toBackupWidget(),
            _toDividerWidget((2 == _index)?Color(0xFF1890ff):Color(0xFF303546)),
            SizedBox(height: 15,),
            _toTerPicWidget(),
            SizedBox(height: 30,),
            _toBindWidget(),
            Spacer(),
            _toUserInfoWidget(),
            SizedBox(height: 60,),
          ],
        ),
      ),
    );
  }

  _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      rightPadding: 15,
      isHideRightWidget:true,
      title: "绑定显示屏终端",
    );
  }

  _toCompanyWidget(){
    return Row(
      children: [
        Container(
          width: 70,
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(left: 15),
          child: Text(
            "所属公司",
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                fontSize: 14,
                height: 1.2
            ),
          ),
        ),
        Container(
          alignment: Alignment.centerLeft,
          child: Text(
            UserRepository.getInstance().userData.companyInfo.companynick,
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                fontSize: 14,
                height: 1.2
            ),
          ),
        ),
      ],
    );
  }

  _toEmptyWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.addressValueNotifier,
      builder: (BuildContext context, CompanyAddressListInfoBean addressBean, Widget child){
        if(_selectAddress == null){
          _selectAddress = addressBean;
        }
        return Container();
      },
    );
  }

  _toChannelOrgWidget(){
    return Visibility(
      visible: AppOverallDistinguish.comefromAiOrWeStudy(),
      child: ValueListenableBuilder(
        valueListenable: _viewModel?.addressValueNotifier,
        builder: (BuildContext context, CompanyAddressListInfoBean addressBean, Widget child){
          if(_selectAddress == null){
            _selectAddress = addressBean;
          }
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: ()async{
              CompanyAddressListInfoBean result = await ChannelOrgListPage.navigatorPush(context, _gps, _selectAddress);
              if(result != null){
                _selectAddress = result;
              }
              setState(() {
                _index = 0;
              });
            },
            child: Row(
              children: [
                Container(
                  width: 70,
                  height: 45,
                  margin: EdgeInsets.only(left: 15),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "所属地址",
                    style: TextStyle(
                        color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                        fontSize: 14,
                        height: 1.2
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      getAddressStr()??"选填",
                      style: TextStyle(
                          color: StringUtils.isNotEmpty(getAddressStr()??"")?ThemeRepository.getInstance().getTextColor_D0E0F7()
                              :ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                          fontSize: 14,
                          height: 1.2
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 15,),
                Image.asset(
                  "images/index_arrow_ico.png",
                  width: 6,
                ),
                SizedBox(width: 15,)
              ],
            ),
          );
        },
      ),
    );
  }

  String getAddressStr(){
    if(_selectAddress==null || (!AppOverallDistinguish.comefromAiOrWeStudy()))return "";
    return "${_selectAddress?.branchname??""}/${_selectAddress?.address}";
  }

  _toDividerWidget(Color color){
    return Container(
      height: 1,
      color: color,
      margin: const EdgeInsets.only(
          left: 85,
          right: 15
      ),
    );
  }

  _toPositionWidget(){
    return Row(
      children: [
        Container(
          width: 70,
          height: 45,
          margin: EdgeInsets.only(left: 15),
          alignment: Alignment.centerLeft,
          child: Text(
            "摆放位置",
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                fontSize: 14,
                height: 1.2
            ),
          ),
        ),
        Expanded(
          child: Container(
            alignment: Alignment.centerLeft,
            child: VgTextField(
              controller: _positionController,
              focusNode: _positionFocusNode,
              maxLines: 1,
              minLines: 1,
              maxLength: 30,
              decoration: InputDecoration(
                border: InputBorder.none,
                counterText: "",
                hintText: "选填",
                hintStyle: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getHintGreenColor_5E687C(),
                    fontSize: 14,
                    height: 1.2
                ),
              ),
              style: TextStyle(
                  fontSize: 14,
                  height: 1.2,
                  color: ThemeRepository.getInstance()
                      .getTextMainColor_D0E0F7()),
              onChanged: (value){
                _position = value;
                setState(() {
                });
              },
            ),
          ),
        ),
        SizedBox(width: 15,),
        Container(
          width: 1,
          height: 25,
          color: Color(0xFF303546),
        ),
        Container(
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Image.asset(
            "images/icon_set_ter_pos.png",
            width: 24,
          ),
        ),
      ],
    );
  }

  _toBackupWidget(){
    return Row(
      children: [
        Container(
          width: 70,
          height: 45,
          margin: EdgeInsets.only(left: 15),
          alignment: Alignment.centerLeft,
          child: Text(
            "备注信息",
            style: TextStyle(
                color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                fontSize: 14,
                height: 1.2
            ),
          ),
        ),
        Expanded(
          child: Container(
            alignment: Alignment.centerLeft,
            child: VgTextField(
              controller: _backupController,
              focusNode: _backupFocusNode,
              maxLines: 1,
              minLines: 1,
              maxLength: 30,
              decoration: InputDecoration(
                border: InputBorder.none,
                counterText: "",
                hintText: "选填",
                hintStyle: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getHintGreenColor_5E687C(),
                    fontSize: 14,
                    height: 1.2
                ),
              ),
              style: TextStyle(
                  fontSize: 14,
                  height: 1.2,
                  color: ThemeRepository.getInstance()
                      .getTextMainColor_D0E0F7()),
              onChanged: (value){
                _backup = value;
                setState(() {
                });
              },
            ),
          ),
        ),
        SizedBox(width: 15,)
      ],
    );
  }

  void _chooseSinglePicAndClip() async {
    String fileUrl =
    await MatisseUtil.clipOneImage(context, scaleX: 1, scaleY: 1,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        });
    if (fileUrl == null || fileUrl == "") {
      return null;
    }
    _terminalPicUrl = fileUrl;
    setState(() {});
  }

  _toTerPicWidget(){
    return Row(
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => StringUtils.isEmpty(_terminalPicUrl?? "")
              ?_chooseSinglePicAndClip()
              :TerminalPicDetailPage.navigatorPush(context,
              url: _terminalPicUrl,
              selectMode: SelectMode.Normal,
              clipCompleteCallback: (path, cancelLoadingCallback) {
                _terminalPicUrl = path;
                setState(() {});
                // _bindingViewModel.setTerminalPic(context, itemBean?.id, itemBean?.hsn,
                //     "01", itemBean?.terminalPicurl);
              }),
          child: Container(
            height: 90,
            width: 90,
            margin: EdgeInsets.only(left: 15, right: 15),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Container(
                width: 90,
                height: 90,
                child: VgCacheNetWorkImage(
                  _terminalPicUrl ?? "",
                  placeWidget: Container(color: ThemeRepository.getInstance().getCardBgColor_21263C()),
                  emptyWidget:
                  Image.asset("images/binding_terminal_add_pic_ico.png"),
                ),
              ),
            ),
          ),
        ),
        Text(
          "上传终端显示屏摆放场景照片（选填）",
          style: TextStyle(
              color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
              fontSize: 12,
              height: 1.2
          ),
        )
      ],
    );
  }

  _toBindWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(StringUtils.isNotEmpty(_terminalPicUrl) && !PhotoPreviewToolUtils.isNetUrl(_terminalPicUrl)){
          VgMatisseUploadUtils.uploadSingleImage(
              _terminalPicUrl,
              VgBaseCallback(onSuccess: (String netPic) {
                if (StringUtils.isNotEmpty(netPic)) {
                  doBind();
                } else {
                  VgToastUtils.toast(context, "图片上传失败");
                }
              }, onError: (String msg) {
                VgToastUtils.toast(context, msg);
              }));
        }else{
          doBind();
        }

      },
      child: Container(
        decoration: BoxDecoration(
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            borderRadius: BorderRadius.circular(8)
        ),
        height: 40,
        alignment: Alignment.center,
        margin: EdgeInsets.symmetric(horizontal: 15),
        child: Text(
          "绑定",
          style: TextStyle(
              fontSize:15,
              color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
              height: 1.2
          ),
        ),
      ),
    );
  }

  _toUserInfoWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          VgStringUtils.subStringAndAppendSymbol(
              UserRepository.getInstance().of(context)?.comUser?.name , 12,
              symbol: "...") ?? "",
          style: new TextStyle(
              color: Color(0xFF5E687C),
              fontSize: 12,
              height: 1.2
          ),
        ),
        SizedBox(
          width: 6,
        ),
        Text(
          UserRepository.getInstance().of(context)?.comUser?.phone ?? "",
          style: TextStyle(
              color: Color(0xFF5E687C),
              fontSize: 12,
              height: 1.2
          ),
        ),
      ],
    );
  }

  void doBind() async{
    if("00" == _data.have) {
      _viewModel.scanThenOperations(widget?.hsn, "13");
      RouterUtils.pop(context, result: true);
    }else if("01" == _data.have){
      if(StringUtils.isNotEmpty(_terminalPicUrl)){
        VgHudUtils.show(context, "保存中");
        VgMatisseUploadUtils.uploadSingleImage(
            _terminalPicUrl,
            VgBaseCallback(onSuccess: (String netPic) {
              if (StringUtils.isNotEmpty(netPic)) {
                _toSaveHttp(netPic);
              } else {
                VgHudUtils.hide(context);
                VgToastUtils.toast(context, "图片上传失败");
              }
            }, onError: (String msg) {
              VgHudUtils.hide(context);
              VgToastUtils.toast(context, msg);
            }));
      }else{
        _toSaveHttp("");
      }
    }
    else if("02" == _data?.have){
      //跳转到绑定确认的页面
      _viewModel.scanThenOperations(widget?.hsn, "14");
      dynamic result = await RouterUtils.pushAndPop(context,
          BindTerminalInfoConfirmPage(hsn: widget?.hsn,
            defaultName: (StringUtils.isNotEmpty(_backup)?_backup:(_data?.terName??"终端显示屏1")),
            defaultPosition: (_position??"请选择"),), result: true);
      if(result == null){
        _viewModel.exitBindTerminal(widget?.hsn);
      }
    }

  }

  _toSaveHttp(String picurl){
    //扫码登录并绑定
    String cbid = _selectAddress?.cbid??"";
    BindingTermialEditUploadBean _uploadBean = BindingTermialEditUploadBean();
    _uploadBean
      ..flg = "00"
      ..terminal_name = _backup??""
      ..terminal_picurl = picurl??""
      ..backup = _backup??""
      ..position = _position??""
      ..rcaid = _data?.rcaid
      ..hsn = widget?.hsn
      ..caid = _data?.caid??""
      ..cbid  = cbid??""
    ;
    _viewModel.toSaveTerminalInfo(context, _uploadBean, showHud: false, callback: (){
      RouterUtils.pop(context, result: true);
      _viewModel.scanThenOperations(widget?.hsn, "16");
      VgEventBus.global.send(new TerminalNumberUpdateEvent("新增绑定终端"));
    });
  }
}